package com.hlg.xboot.utils;

import com.hlg.xboot.constants.AppConstants;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>Description: api辅助接口</p>
 * <p>Copyright: Copyright (c) 2016</p>
 * <p>Company: 中视数讯</p>
 * <p>Site: www.digi-zones.com</p>
 * <p>myblog: http://blog.csdn.net/xyang81</p>
 *
 * @author 杨信
 * @version 1.0
 * @date 2016/10/31
 */
public class APIHelper {

    // APIToken混淆参数，防止反向推断时加密的Token值
    private static final String APITOKEN_SLOT = "adf;o234920@3#@$@-=~342ISajzxvaf/AskDFjiw/%^^@#@$@";

    /**
     * 从请求头中获取客户端api_token
     * @param request
     * @return
     */
    public static String getApiToken(HttpServletRequest request) {
        String apiToken = request.getHeader(AppConstants.API_TOKEN);
        return StringUtils.isEmpty(apiToken) ? "" : apiToken;
    }

    /**
     * 根据指定token获取用户会话信息
     * @param request
     * @return
     */
    public static <T> T getLoginUser(String apiToken,HttpServletRequest request) {
        return (T) request.getSession().getAttribute(apiToken);
    }

    /**
     * 获取当前登录用户信息
     * @param request
     * @param <T>
     * @return
     */
    public static <T> T getLoginUser(HttpServletRequest request) {
        String apiToken = getApiToken(request);
        return getLoginUser(apiToken,request);
    }

    /**
     * 保存登录用户到redis缓存中
     * @param user 用户信息
     * @param apiToken 用户api token
     */
    public static void saveLoginUser(Object user, String apiToken, HttpServletRequest request) {
        request.getSession().setAttribute(apiToken, user);
    }

    /**
     * 更新当前登录用户信息
     * @param user
     * @param request
     */
    public static void saveLoginUser(Object user, HttpServletRequest request) {
        request.getSession().setAttribute(getApiToken(request), user);
    }

    /**
     * 删除登录用户信息
     * @param apiToken 用户api_token
     */
    public static void removeLoginUser(String apiToken, HttpServletRequest request) {
        if (StringUtils.isEmpty(apiToken)) {
            return;
        }
        request.removeAttribute(apiToken);
    }

    /**
     * 根据手机号生成一个api_token
     * @param uuid 用户唯一ID
     * @return
     */
    public static String generateApiToken(String uuid) {
        return DigestUtils.md5Hex(uuid + APITOKEN_SLOT);
    }

    /**
     * 从请求头中获取客户端channel
     * @param request
     * @return
     */
    public static Integer getChannel(HttpServletRequest request) {
        String channel = request.getHeader(AppConstants.CHANNEL);
        return StringUtils.isEmpty(channel) ? -1 : Integer.parseInt(channel);
    }
}
